package com.jumper.study.admin.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumper.study.admin.dto.req.LessonContentReq;
import com.jumper.study.admin.dto.req.LessonReq;
import com.jumper.study.admin.dto.req.LessonSearchReq;
import com.jumper.study.admin.dto.req.ModelStatusReq;
import com.jumper.study.admin.dto.resp.LessonChapterResp;
import com.jumper.study.admin.dto.resp.LessonEbookResp;
import com.jumper.study.admin.dto.resp.LessonListResp;
import com.jumper.study.admin.dto.resp.LessonResp;
import com.jumper.study.admin.service.LessonChapterService;
import com.jumper.study.admin.service.LessonEbookService;
import com.jumper.study.admin.service.LessonService;
import com.jumper.study.common.api.CommonPageResult;
import com.jumper.study.common.api.CommonResult;
import com.jumper.study.common.api.ResultCode;
import com.jumper.study.db.dto.LessonDto;
import com.jumper.study.db.model.LessonChapter;
import com.jumper.study.db.model.LessonEbook;
import com.jumper.study.db.model.Lesson;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;




@RestController
@RequestMapping("/api/backend/lessons")
public class LessonController {
    @Autowired
    private LessonService lessonService;

    @Autowired
    private LessonChapterService chapterService;

    @Autowired
    private LessonEbookService ebookService;

    @PostMapping("")
    public CommonPageResult<List<LessonListResp>> getList(@RequestBody LessonSearchReq req) {
        Page<LessonDto> p = Page.of(req.getPage(), req.getLimit());
        List<LessonDto> lessons = lessonService.listWithCategory(p, req).getRecords();
        List<LessonListResp> resp = lessons.stream().map(
            dto -> new LessonListResp(dto.getId(), dto.getTitle(), dto.getCategoryId(), dto.getCategoryTitle(), dto.getThumb(),
                dto.getSummary(), dto.getPrice(), dto.getMarketPrice(), dto.getRecommend(), dto.getOnself(),
                dto.getTeachers(), dto.getBuyCount(), dto.getChapterCount(), dto.getEbookCount(), dto.getSort(),
                dto.getUpdatedAt())
            ).toList();

        return CommonPageResult.restPage(p.getCurrent(), p.getSize(), p.getTotal(), resp);
    }
    
    @GetMapping("/{id}")
    public CommonResult<LessonResp> getItem(@PathVariable Long id) {
        Lesson lesson = lessonService.getById(id);
        if (lesson == null) {
            return CommonResult.notFound("课程不存在");
        }
        LessonResp resp = new LessonResp(lesson.getId(), lesson.getCategoryId(), lesson.getTitle(), lesson.getThumb(), 
                lesson.getSummary(), lesson.getSummary(), lesson.getPrice(), lesson.getMarketPrice(), 
                lesson.getRecommend(), lesson.getOnself(), lesson.getTeachers(), lesson.getSort(), lesson.getUpdatedAt());

        return CommonResult.success(resp);
    }

    @GetMapping("/{id}/content")
    public CommonResult<String> getContent(@PathVariable Long id) {
        Lesson lesson = lessonService.getById(id);
        if (lesson == null) {
            return CommonResult.notFound("课程不存在");
        }

        return CommonResult.success(lesson.getContent());
    }

    @PostMapping("/{id}/content")
    public CommonResult<Boolean> updateContent(@PathVariable Long id, @RequestBody LessonContentReq req) {
        Lesson lesson = lessonService.getById(id);
        if (lesson == null) {
            return CommonResult.notFound("课程不存在");
        }
        lesson.setContent(req.getContent());
        boolean result = lessonService.updateById(lesson);

        return CommonResult.success(result);
    }

    @PostMapping("/")
    public CommonResult<Boolean> create(@RequestBody @Validated LessonReq req) {
        Lesson lesson = lessonService.getByTitle(req.getTitle(), null);
        if (lesson != null) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED.getCode(), "课程已存在");
        }

        lesson = new Lesson();
        lesson.setTitle(req.getTitle());
        lesson.setThumb(req.getThumb());
        lesson.setCategoryId(req.getCategoryId());
        lesson.setSummary(req.getSummary());
        lesson.setPrice(req.getPrice());
        lesson.setMarketPrice(req.getMarketPrice());
        lesson.setTeachers(req.getTeachers());
        lesson.setRecommend(req.getRecommend());
        lesson.setSort(req.getSort());

        boolean result = lessonService.save(lesson);
        return CommonResult.success(result);
    }
    
    @PostMapping("/{id}")
    public CommonResult<Boolean> update(@PathVariable Long id, @RequestBody @Validated LessonReq req) {
        Lesson lesson = lessonService.getByTitle(req.getTitle(), id);
        if (lesson != null) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED.getCode(), "课程名称已存在" + id);
        }

        lesson = lessonService.getById(id);
        if (lesson == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }
        
        lesson.setTitle(req.getTitle());
        lesson.setThumb(req.getThumb());
        lesson.setCategoryId(req.getCategoryId());
        lesson.setSummary(req.getSummary());
        lesson.setPrice(req.getPrice());
        lesson.setMarketPrice(req.getMarketPrice());
        lesson.setTeachers(req.getTeachers());
        lesson.setRecommend(req.getRecommend());
        lesson.setSort(req.getSort());

        boolean result = lessonService.updateById(lesson);
        return CommonResult.success(result);
    }
    

    @PostMapping("/recommend")
    public CommonResult<Boolean> recommendLessons(@RequestBody @Validated ModelStatusReq req) {
        boolean result = lessonService.recommendBatchById(req.getIds(), req.status());

        return CommonResult.success(result);
    }

    @PostMapping("/onself")
    public CommonResult<Boolean> onselfLessons(@RequestBody @Validated ModelStatusReq req) {
        boolean result = lessonService.onselfBatchById(req.getIds(), req.status());

        return CommonResult.success(result);
    }

    @DeleteMapping("/{id}")
    @Transactional
    public CommonResult<Boolean> delete(@PathVariable Long id) {
        Lesson lesson = lessonService.getById(id);
        if (lesson == null) {
            return CommonResult.success(true);
        }

        //todo 需要确认是否有学员开通课程
        //同时删除对应的章节和资料
        boolean result = lessonService.removeById(id);
        result = chapterService.removeByLessonId(id);
        result = ebookService.removeByLessonId(id);
        return CommonResult.success(result);
    }
    
    @GetMapping("/{id}/chapters")
    public CommonResult<List<LessonChapterResp>> chapters(@PathVariable Long id) {
        Lesson lesson = lessonService.getById(id);
        if (lesson == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), "课程不存在");
        }
        List<LessonChapter> chapters = chapterService.getByLessonId(id);
        List<LessonChapterResp> resp = chapters.stream()
                .map(c -> new LessonChapterResp(c.getId(), c.getTitle(), c.getLessonId(), lesson.getTitle(), 
                c.getVideo(), c.getDuration(), c.getOnself(), c.getSort(), c.getUpdatedAt())
                ).toList();
        return CommonResult.success(resp);
    }
    
    @GetMapping("/{id}/ebooks")
    public CommonResult<List<LessonEbookResp>> ebooks(@PathVariable Long id) {
        Lesson lesson = lessonService.getById(id);
        if (lesson == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), "课程不存在");
        }
        List<LessonEbook> ebooks = ebookService.getByLessonId(id);
        List<LessonEbookResp> resp = ebooks.stream()
                .map(e -> new LessonEbookResp(e.getId(), e.getLessonId(), e.getTitle(), lesson.getTitle(), e.getFile(), e.getOnself(), e.getSort(), e.getUpdatedAt())
                ).toList();
        return CommonResult.success(resp);
    }
    
}
